<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3 图片懒加载：getBoundingClientRect</title>
  <style>
    .box {
      display: flex;
      flex-flow: row wrap;
      justify-content: space-between;
      margin: 700px auto;
      width: 1200px;
      box-sizing: border-box;
      border: solid 2px orange;
    }

    .box li {
      margin: 10px 0;
      background: #eee url("https://fp1.fghrsh.net/2021/03/09/4034d1da915426d4843d46aa61eda956.gif") no-repeat center center;
    }

    img.lazyImg {
      width: 280px;
      height: 280px;
      box-sizing: border-box;
      opacity: 0;
      transition: opacity 0.8s;
    }
  </style>
</head>

<body>
  <ul class="box">
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/9f50b5d49605e71478f4871cf6a76f8e.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/eebe65fa733520365be4f3ed6d1705a3.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/86f7917c4db8082a49b66608c57db0a5.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/92153b42d5dbe6522cf25da580dcb80e.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/8de0d40adac186eaffd968842f8467f4.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/02/09/ee118e49a84068e4bfc3867716e6f754.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/01/11/d6a7d63acd7d9657225e01c91d962795.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/eebe65fa733520365be4f3ed6d1705a3.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/03/09/86f7917c4db8082a49b66608c57db0a5.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/01/11/d6a7d63acd7d9657225e01c91d962795.jpg">
    </li>
    <li><img class="lazyImg" src="" img-src="https://fp1.fghrsh.net/2021/02/09/ee118e49a84068e4bfc3867716e6f754.jpg">
    </li>
  </ul>

  <!-- <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script> -->
  <script src="../../node_modules/lodash/lodash.min.js"></script>
  <script>

    let box = document.querySelector(".box"),
      imgs = document.querySelectorAll('img.lazyImg');

    function handleImage() {
      imgs.forEach(img => {
        let imgHeight = img.getBoundingClientRect().top,
          viewHeight = document.documentElement.clientHeight;
        if (imgHeight <= viewHeight) {
          img.src = img.getAttribute('img-src')
          img.onload = function () {
            img.style.opacity = 1
          }
        }
      })
    }
    window.addEventListener("scroll", _.throttle(handleImage, 500));
  </script>
</body>

</html>